<template>
	<div class="water-zone-container">
		<div class="water-zone-header">
			<span>河流：</span>
			<el-select size="small" v-model="riverid" placeholder="请选择河流">
				<el-option v-for="dict in riverList" :key="dict.value" :label="dict.label"
					:value="dict.value"></el-option>
			</el-select>
			<span class="water-zone-name-span">功能区域名称：</span>
			<el-input size="small" class="water-zone-name" v-model="firstfuncarea" placeholder="请输入功能区域名称"></el-input>
			<el-button class="query-btn water-zone-btn" type="primary" icon="el-icon-search" size="mini"
				@click="handleQuery">查询</el-button>
			<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
		</div>
		<div class="water-zone-sub-header">
			<el-button type="primary" icon="el-icon-plus" size="mini" plain v-hasPermi="['system:user:add']"
				@click="addForm">新增</el-button>
			<!-- <el-button type="success" plain icon="el-icon-edit" size="mini" v-hasPermi="['system:user:edit']">修改</el-button> -->
			<el-button type="danger" icon="el-icon-delete" size="mini" plain v-hasPermi="['system:user:remove']"
				@click="handleDelete">删除</el-button>
			<!-- <el-button type="warning" icon="el-icon-download" size="mini" plain
				v-hasPermi="['system:user:export']">导出</el-button> -->

		</div>
		<div class="water-zone-main">
			<el-table ref="multipleTable" v-loading="loading" :data="tableData" tooltip-effect="dark"
				style="width: 100%" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column label="河流">
					<template slot-scope="scope">{{ scope.row.riverName }}</template>
				</el-table-column>
				<el-table-column prop="firstfuncarea" label="功能区域名称">
				</el-table-column>
				<el-table-column prop="funcleveltxt" label="功能区级别" show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="funclength" label="长度" show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="monifrequency" label="监测频次" show-overflow-tooltip>
				</el-table-column>
				<el-table-column prop="compliancetimes" label="年达标次数" show-overflow-tooltip>
				</el-table-column>
				<el-table-column label="操作" align="center" width="150">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
							v-hasPermi="['system:menu:edit']">修改</el-button>
						<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
							v-hasPermi="['system:menu:remove']">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-dialog title="添加水功能区信息" :visible.sync="dialogFormVisible" width="950px">
			<el-form ref="waterform" :model="waterData" :rules="ruleForm" label-width="135px">
				<el-row>
					<el-col :span="12">
						<el-form-item prop="riverid" label="河流">
							<el-select v-model="waterData.riverid" class="select-width" placeholder="请选择河流">
								<el-option v-for="dict in riverList" :key="dict.value" :label="dict.label"
									:value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="firstfuncarea" label="功能区名称">
							<el-input v-model="waterData.firstfuncarea" placeholder="请输入功能区名称"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="funclevel" label="功能区级别">
							<el-select v-model="waterData.funclevel" class="select-width" placeholder="请选择">
								<el-option v-for="dict in dict.type.function_level" :key="dict.value"
									:label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="parentfunc" label="所属一级功能区">
							<el-select v-model="waterData.parentfunc" class="select-width" placeholder="请选择">
								<el-option v-for="item in regionListLevel1" :key="item.code" :label="item.name"
									:value="item.code"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="region" label="行政区划">
							<el-select v-model="waterData.region" class="select-width" placeholder="请选择行政区划">
								<el-option v-for="item in regionList" :key="item.code" :label="item.name"
									:value="item.code"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="startlocationx" label="水功能区起点经度">
							<el-input v-model="waterData.startlocationx" placeholder="请输入水功能区起点经度"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="startlocationy" label="水功能区起点纬度">
							<el-input v-model="waterData.startlocationy" placeholder="请输入水功能区起点纬度"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="endlocationx" label="水功能区终点经度">
							<el-input v-model="waterData.endlocationx" placeholder="请输入水功能区终点经度"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="endLocatony" label="水功能区终点纬度">
							<el-input v-model="waterData.endLocatony" placeholder="请输入水功能区终点纬度"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="waterthirdlevel" label="水资源三级区">
							<el-input v-model="waterData.waterthirdlevel" placeholder="请输入水资源三级区"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="funclength" label="长度">
							<el-input placeholder="请输入长度" v-model="waterData.funclength">
								<template slot="append">（km）</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="mainsegment" label="水质代表断面">
							<el-input v-model="waterData.mainsegment" placeholder="请输入水质代表断面"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="waterarea" label="湖面面积">
							<el-input v-model="waterData.waterarea" placeholder="请输入湖面面积"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="zoneaccording" label="区划依据">
							<el-input v-model="waterData.zoneaccording" placeholder="请输入区划依据"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="purpose" label="水质保护目标">
							<el-input v-model="waterData.purpose" placeholder="请输入水质保护目标"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item prop="monifrequency" label="监测频次">
							<el-input v-model="waterData.monifrequency" placeholder="请输入监测频次"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item prop="compliancetimes" label="年达标次数">
							<el-input v-model="waterData.compliancetimes" placeholder="请输入年达标次数"></el-input>
						</el-form-item>
					</el-col>

				</el-row>

			</el-form>
			<div class="titleBox">
				<p class="title">拐点坐标</p>
				<el-button type="primary" icon="el-icon-plus" size="mini" plain v-hasPermi="['system:user:add']"
					@click="addPoint">增加</el-button>
			</div>
			<el-row v-for="(point, index) in waterData.spinodalList" :key="index" style="margin: 10px 20px;">
				<el-col :span="7">
					<div class="el-col-item">
						<span>拐点编号：</span>
						<el-input class="el-col-inp" v-model="point.pointnum" placeholder="请输入编号"
							style="width: 100%; "></el-input>
					</div>
				</el-col>
				<el-col :span="7">
					<div class="el-col-item">
						<span>经度：</span>
						<el-input class="el-col-inp" v-model="point.longtitute" placeholder="请输入经度"
							style="width: 100%; "></el-input>
					</div>
				</el-col>
				<el-col :span="7">
					<div class="el-col-item">
						<span>纬度：</span>
						<el-input class="el-col-inp" v-model="point.latitute" placeholder="请输入纬度"
							style="width: 100%; "></el-input>
					</div>
				</el-col>
				<el-col :span="3">
					<el-button type="danger" icon="el-icon-delete" size="mini" plain v-hasPermi="['system:user:remove']"
						style="margin-top: 3px;" @click="removePoint(index)">删除</el-button>
				</el-col>
			</el-row>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" :loading="submitLoading" @click="sureFn">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script>
import { getRegionList } from '@/api/dataResources/monitorData/region.js'
import { getRiverSelect } from "@/api/dataResources/monitorData/section.js";
import { getwaterFunctionList, addWaterFunc, deleteWaterFunc, getWaterFuncInfo, editWaterFunc } from '@/api/dataResources/waterJcData/waterFunction.js';
export default {
	name: 'WaterZone',
	dicts: ["function_level"],
	data() {
		return {
			choseList: [],
			loading: false,
			firstfuncarea: '', // 功能区域名称
			riverid: '', //河流id
			tableData: [],

			submitLoading: false,
			regionList: [],
			regionListLevel1: [],
			riverList: [],
			waterData: {
				riverid: '',
				firstfuncarea: '', // 功能区域名称
				funclevel: '', // 功能区域级别
				parentfunc: '', // 功能区域父级名称
				parentfuncName: '',
				region: '',
				startlocationx: '',
				startlocationy: '',
				endlocationx: '',
				endlocatony: '',
				waterthirdlevel: '',
				funclength: '',
				mainsegment: '',
				waterarea: '',
				zoneaccording: '',
				purpose: '',
				monifrequency: '',
				compliancetimes: '',
				spinodalList: [{
					pointnum: '',
					longtitute: '',
					latitute: ''
				}]
			},
			dialogFormVisible: false,
			ruleForm: {
				// mainsegment: [
				// 	{ required: true, message: '请输入水质代表断面', trigger: 'blur' }
				// ],
				riverid: [
					{ required: true, message: '请选择河流', trigger: 'change' }
				],
				firstfuncarea: [
					{ required: true, message: '请输入功能区名称', trigger: 'blur' }
				],
				funclevel: [
					{ required: true, message: '请选择功能区级别', trigger: 'change' }
				],
				// parentfunc: [
				// 	{ required: true, message: '请选择所属一级功能区', trigger: 'change' }
				// ],
				// region: [
				// 	{ required: true, message: '请选择行政区划', trigger: 'change' }
				// ],
				// startlocationx: [
				// 	{ required: true, message: '请输入水功能区起点经度', trigger: 'blur' }
				// ],
				// startlocationy: [
				// 	{ required: true, message: '请输入水功能区起点纬度', trigger: 'blur' }
				// ],
				// endlocationx: [
				// 	{ required: true, message: '请输入水功能区终点经度', trigger: 'blur' }
				// ],
				// endLocatony: [
				// 	{ required: true, message: '请输入水功能区终点纬度', trigger: 'blur' }
				// ],
				// waterthirdlevel: [
				// 	{ required: true, message: '请输入水资源三级区', trigger: 'blur' }
				// ],
				// funclength: [
				// 	{ required: true, message: '请输入长度', trigger: 'blur' }
				// ],
				// waterarea: [
				// 	{ required: true, message: '请输入湖面面积', trigger: 'blur' }
				// ],
				// zoneaccording: [
				// 	{ required: true, message: '请输入区划依据', trigger: 'blur' }
				// ],
				// purpose: [
				// 	{ required: true, message: '请输入水质保护目标', trigger: 'blur' }
				// ],
				// monifrequency: [
				// 	{ required: true, message: '请输入监测频次', trigger: 'blur' }
				// ],
				// compliancetimes: [
				// 	{ required: true, message: '请输入年达标次数', trigger: 'blur' }
				// ]
			}

		}
	},
	created() {
		this.query()
	},
	methods: {
		initFormData() {
			this.waterData = {
				riverid: '',
				firstfuncarea: '', // 功能区域名称
				funclevel: '', // 功能区域级别
				parentfunc: '', // 功能区域父级名称
				parentfuncName: '',
				region: '',
				startlocationx: '',
				startlocationy: '',
				endlocationx: '',
				endlocatony: '',
				waterthirdlevel: '',
				funclength: '',
				mainsegment: '',
				waterarea: '',
				zoneaccording: '',
				purpose: '',
				monifrequency: '',
				compliancetimes: '',
				spinodalList: [{
					pointnum: '',
					longtitute: '',
					latitute: ''
				}]
			}
		},
		async handleUpdate(data) {
			let id = data?.id || '';

			if (!id) {
				this.$message.error('请选择一条数据')
				return
			}
			let res = await getWaterFuncInfo(id);
			if (res.code == 200) {
				this.waterData = res.data
				this.dialogFormVisible = true;
			} else {
				this.$message.error(res.message)
			}
		},
		//获取所属河流下拉选项数据
		getsshl() {
			getRiverSelect().then((response) => {
				this.riverList = response.data.map((item) => ({
					value: item.id,
					label: item.rivername,
				}));
			});
		},

		async getRegionListLevel1() {
			this.regionListLevel1 = []
			let res = await getwaterFunctionList({ firstfuncarea: "", riverid: "" })
			if (res.code == 200) {
				res.rows.map(item => {
					this.regionListLevel1.push({
						code: item.firstfuncarea,
						name: item.firstfuncarea
					})
				})
			}
		},
		async getRegionList() {
			let res = await getRegionList();
			if (res.code == 200) {
				this.regionList = res.rows;
			}
		},

		sureFn() {
			this.$refs['waterform'].validate((valid) => {
				if (valid) {
					this.addWater()
				} else {
					return false;
				}
			});
		},
		addPoint() {
			this.waterData.spinodalList.push({
				pointnum: '',
				longtitute: '',
				latitute: ''
			});
		},
		removePoint(index) {
			this.waterData.spinodalList.splice(index, 1);
			if (this.waterData.spinodalList.length == 0) {
				this.waterData.spinodalList.push({
					pointnum: '',
					longtitute: '',
					latitute: ''
				});
			}
		},
		addForm() {
			this.initFormData()
			this.dialogFormVisible = true;
		},
		query() {
			this.getsshl()
			this.getRegionList();
			this.getRegionListLevel1();
			this.getwaterFunctionList();

		},
		async deleteWaterFunc(id) {
			try {
				// 如果没有传入id，则从选中列表中获取
				if (!id) {
					if (this.choseList.length === 0) {
						this.$message.error('请选择要删除的数据');
						return;
					}
					// 支持单个或批量删除
					id = this.choseList.map(item => item.id).join(',');
				}

				// 确认有要删除的ID
				if (!id) {
					this.$message.error('请选择要删除的数据');
					return;
				}

				// 执行删除操作
				const res = await deleteWaterFunc(id);
				if (res.code === 200) {
					this.$message.success('删除成功');
					this.query(); // 刷新列表
				} else {
					this.$message.error(res.message || '删除失败');
				}
			} catch (error) {
				this.$message.error('删除失败，请稍后重试');
				console.error(error);
			}
		},
		handleDelete(data) {
			this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.deleteWaterFunc(data?.id)
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消删除'
				})
			})
		},
		getwaterFunctionList() {
			this.loading = true;
			getwaterFunctionList({ firstfuncarea: this.firstfuncarea, riverid: this.riverid }).then(res => {
				if (res.code == 200) {
					// 为每条数据根据riverid设置riverName
					this.tableData = res.rows.map(item => {

						const river = this.riverList.find(riverItem => riverItem.value == item.riverid);
						let funcleveltxt = ''
						for (let itemk of this.dict.type.function_level) {
							if (itemk.value == item.funclevel) {
								funcleveltxt = itemk.label
							}
						}
						return {
							funcleveltxt,
							...item,
							riverName: river ? river.label : ''
						};
					});

				} else {
					this.tableData = []
					this.$message.error(res.msg)
				}
				this.loading = false;
			})
		},
		resetQuery() {
			this.firstfuncarea = ''
			this.riverid = ''
		},
		handleQuery() {
			this.getwaterFunctionList()
		},
		handleSelectionChange(val) {
			this.choseList = val;
		},
		async addWater() {
			this.submitLoading = true;
			try {
				let res;
				if (this.waterData.id) {
					res = await editWaterFunc(this.waterData);
				} else {
					res = await addWaterFunc(this.waterData);
				}

				if (res.code === 200) {
					this.$message.success(res.msg || (this.waterData.id ? '修改成功' : '新增成功'));
					this.query();
					this.dialogFormVisible = false;
				} else {
					this.$message.error(res.msg || (this.waterData.id ? '修改失败' : '新增失败'));
				}
			} catch (error) {
				this.$message.error(error.message || (this.waterData.id ? '修改失败' : '新增失败'));
				console.error(error);
			} finally {
				this.submitLoading = false;
			}
		}
	},
	mounted() {
	}
}

</script>
<style lang="scss" scoped>
.water-zone-container {
	width: 100%;
	height: 100%;
	padding: 15px;
	box-sizing: border-box;
}

.water-zone-header {
	display: flex;
	align-items: center;
	margin-bottom: 10px;

	span {
		margin-right: 10px;
	}
}

.water-zone-name {
	width: 200px;
}

.water-zone-btn {
	margin-left: 10px;
}

.water-zone-name-span {
	margin-left: 10px;
}

.water-zone-main {
	margin-top: 10px;
}

.select-width {
	width: 100%;

}

.titleBox {
	height: 50px;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1px solid #dfe4ed;
	margin: 0 20px 20px 20px;
	position: relative;

	&::before {
		display: block;
		content: "";
		width: 3px;
		height: 16px;
		background: #307eff;
	}

	.title {
		font-size: 16px;
		color: #000;
		position: absolute;
		left: 10px;
		font-weight: 500;
	}
}

.el-col-item {
	display: flex;
	align-items: baseline;
	white-space: nowrap;
}

.el-col-inp {
	width: 160px !important;
}
</style>
